import React, { useEffect, useState } from 'react'
import { NavBar } from 'antd-mobile'
import '../style/order.css'
import Address from '../order/Address'
import Shopping from '../order/shopping'
import { useParams } from 'react-router-dom'
import { getDetail } from '../../../api/yjr/yjr_api'
import { useNavigate } from 'react-router-dom';
import { SubmitBar } from 'react-vant';
import { postZiFu, getStatic } from '../../../api/yjr/yjr_api'
import { Cell, Popup, PopupPosition } from 'react-vant'

export default React.memo( function Order() {
  const { id } = useParams()

  const shopId = id?.split(':')
  const shopIdJoin = shopId?.join('')
  const history = useNavigate()
  const [details, setDetails] = useState<any>([])
  const [show, setShow] = useState<boolean>(false)
  const [flag, setFlag] = useState<boolean>(false)

  const back = () => {
    sessionStorage.setItem('integralShop', JSON.stringify({ flag: true }))
    history(-1)
  }

  const getDetails = async () => {
    const res = await getDetail({ id: id })
    setDetails(res.data.detail);
  }
  const [state, setState] = useState<PopupPosition>('')

  const [timeLeft, setTimeLeft] = useState(60 * 60); // 1 小时 = 3600 秒

  const handleSubmit = async (details: any) => {
    await getStatic(details._id, 1);
    let detail = JSON.parse(sessionStorage.getItem('details') || '[]');
    if (!Array.isArray(detail)) {
      detail = [];
    }
    detail.push(details);
    sessionStorage.setItem('details', JSON.stringify(detail));

    detail.map((ele: any) => {
      if (ele._id === details._id) {
        setFlag(true)
        // setShow(true)
        const intervalId = setInterval(() => {
          setTimeLeft((prevTime) => prevTime - 1);
          // setShow(true)

          if (timeLeft == 0) {
            clearInterval(intervalId);
            // setShow(false)
          }
        }, 1000);
        sessionStorage.setItem('show', JSON.stringify(show));
      }
    })
    setState('bottom')
  };

  const formatTime = (seconds: any) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  };


  const onClose = () => setState('')

  const handleClose = async (details: any) => {
    const data = await postZiFu(details);
    if (data.data.code === 200) {
      await getStatic(details._id, 2);
      let detail = JSON.parse(sessionStorage.getItem('details') || '[]');
      if (!Array.isArray(detail)) {
        detail = [];
      }
      detail.push(details);
      sessionStorage.setItem('details', JSON.stringify(detail));
      window.location.href = data.data.result;
    }
  }

  useEffect(() => {
    getDetails()
  }, [])

  return (
    <div className='order'>
      <div className='header'>
        <NavBar onBack={back}>提交订单</NavBar>
      </div>
      <div className='body'>
        <Address item={id} />
        <Shopping id={shopIdJoin} />

        <div className='total'>
          <p style={{ marginBottom: '.5rem' }}>商品小计 <span className='order-span'>{details.integral - details.freight} (<span style={{ color: 'red' }}> - {details.freight}</span>)积分</span></p>
          <hr style={{ border: 'none', borderTop: '1px solid #f0f0f0', width: '96%' }} />
          <p style={{ marginTop: '.5rem' }}>运费抵扣 <span className='order-span'>{details.freight}积分</span></p>
        </div>

        <div className="demo-submit-bar"><SubmitBar price={`${details.integral - details.freight}00`} buttonText={!flag ? "提交订单" : formatTime(timeLeft)} onSubmit={() => handleSubmit(details)} disabled={show} /></div>
        <Popup
          visible={state === 'bottom'}
          style={{ height: '40%' }}
          position='bottom'
          onClose={onClose}
        >
          <Shopping id={shopIdJoin} />
          <div className="demo-submit-bar"><SubmitBar price={`${details.integral - details.freight}00`} buttonText="确定支付" onSubmit={() => handleClose(details)} /></div>
        </Popup>
      </div>
    </div>
  )
})
